package com.th.supcom.pds.recipefee.client.mvc;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.fc.component.editor.client.EMREditorPanel;
import net.carefx.framework.container.client.context.AppContext;
import net.carefx.framework.container.client.page.PageContext;

import com.extjs.gxt.ui.client.Style.HideMode;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.print.client.DynamicPrintModel;
import com.th.supcom.framework.print.client.GridDataSetModel;
import com.th.supcom.framework.print.client.GridRowModel;
import com.th.supcom.framework.print.client.PrintUtils;
import com.th.supcom.pds.common.client.commom.PdsAuditPrescServiceFactory;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.config.client.model.PhamWindowConfigModel;
import com.th.supcom.pds.internal.client.model.PatientInfoModel;
import com.th.supcom.pds.recipefee.client.business.RecipeFeeBusiness;
import com.th.supcom.pds.recipefee.client.common.RecipeFeeModuleEvents;
import com.th.supcom.pds.recipefee.client.widget.OutputWindowCombox;
import com.th.supcom.pds.recipefee.client.widget.RecipeFeeMainPanel;
import com.th.supcom.pds.recipefee.client.widget.RecipeFeeUtils;
import com.th.supcom.pds.sortingdrug.client.model.PdsPrescDetailInfoModel;

/**
 * 收方收费视图.
 * 
 * @author 杨冲
 */
public class RecipeFeeView extends View
{
    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";
    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";
    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";
    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
    private EMREditorPanel m_editorPanel;
    private RecipeFeeMainPanel m_recipeFeeMainPanel;
    List <PdsPrescDetailInfoModel> putDrugresult = new ArrayList <PdsPrescDetailInfoModel> ();
    private final String dispensaryCode=ClientUtils.getOrgModel().getOrgCode();
    private final String dispensaryName=ClientUtils.getOrgModel().getOrgName();
    private final String IP=AppContext.get ().get ("IP");
    private String recptNo="";
    final List <PdsPrescDetailInfoModel> unPutDrugresult = new ArrayList <PdsPrescDetailInfoModel> ();
    //选中的数据
    List <PdsPrescDetailInfoModel> prescresult = null;
    /**
     * @param controller
     */
    public RecipeFeeView (final Controller controller)
    {
        super (controller);
    }

    @Override
    protected void handleEvent (final AppEvent event)
    {
        if (RecipeFeeModuleEvents.UI_INIT.equals (event.getType ()))
        {
            final PageContext context = event.getData ();
            this.initUI (context);
            return;
        }
        if (RecipeFeeModuleEvents.RECIPEFEE_ADDPLASTICBAG.equals (event.getType ()))
        {
            //弹出塑料代的对话框
            m_recipeFeeMainPanel.poupWindow();
            return;
        }
        if (RecipeFeeModuleEvents.RECIPEFEE_QUERY.equals (event.getType ()))
        {
            //根据处方号查询处方主记录和患者信息
            Map <String, Object>map=new HashMap <String, Object> ();
            map.put ("prescNo", m_recipeFeeMainPanel.getFields ().getRecipeNoField ().getValue ());
            map.put ("flag", 1);
            map.put ("dispensaryCode", dispensaryCode);
            // 按处方号或者patientId查询
            RecipeFeeBusiness.queryByPrescNo (map,m_recipeFeeMainPanel);
            return;
        }
        if (RecipeFeeModuleEvents.LOAD_DETAIL.equals (event.getType ()))
        {
            //加载记录明细
            RecipeFeeBusiness.loadData (m_recipeFeeMainPanel);
            return;
        }
        if (RecipeFeeModuleEvents.CANCEL_DETAIL.equals (event.getType ()))
        {
            //取消记录明细
            RecipeFeeBusiness.cancelPrescDetail(m_recipeFeeMainPanel);
            return;
        }
        if (RecipeFeeModuleEvents.RECIPEFEE_CONFIRM.equals (event.getType ()))
        {
             PatientInfoModel patientInfoModel=m_recipeFeeMainPanel.getPatientInfoModel ();
            Map <String, Object>map=new HashMap <String, Object> ();
            map.put ("patientId", patientInfoModel.getPatiId ());
            map.put ("area",ClientUtils.getOrgModel().getOrgAreaCode());//院区编码 patientInfoModel.getHospitalAreaCode ()
            map.put ("visitId",patientInfoModel.getVisitId () );//就诊序号
            map.put ("operator", ClientUtils.geteEmpModel().getEmpCode());//
            map.put ("IP", IP);
            map.put ("dispensaryCode", dispensaryCode);
            map.put ("trackData", patientInfoModel.getTrackData ());
            RecipeFeeBusiness.confirm (m_recipeFeeMainPanel,map);
            return;
        }
        if (RecipeFeeModuleEvents.RECIPEFEE_CLEAR.equals (event.getType ()))
        {
            RecipeFeeUtils.clearInfo (m_recipeFeeMainPanel);
            return;
        }
        if (RecipeFeeModuleEvents.RECIPEFEE_PRINT.equals (event.getType ()))
        {
            // 打印
            Map <String, Object>map=event.getData ("result");
            recptNo=(String) map.get ("rcptNo");
            startPrint (map);
        }
    }

    /**
     * 初始化容器面板.
     * 
     * @param context
     */
    private void initUI (final PageContext context)
    {
        /** 主窗口容器. */
        LayoutContainer mainLayoutContainer;
        mainLayoutContainer = context.getContainer ();
        mainLayoutContainer.setLayout (new FitLayout ());
        mainLayoutContainer.setHideMode (HideMode.OFFSETS);
        m_recipeFeeMainPanel = new RecipeFeeMainPanel ();
        m_editorPanel = PrintUtils.createReportPanel ();
        mainLayoutContainer.add (m_recipeFeeMainPanel);
        mainLayoutContainer.add (m_editorPanel);
    }

    /**
     * 修改分配的窗口
     * @param result
     */
    private void modifyWindow (final Long window,final String windowName)
    {
        PdsAuditPrescServiceFactory.getRecipeFeeService ().modifyWindow (prescresult,ClientUtils.getOrgModel().getOrgCode(),
                                                                         window, new AsyncCallback <Void> ()
                                                                         {

                                                                             @Override
                                                                             public void onFailure (final Throwable caught)
                                                                             {
                                                                                 ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                                              null);
                                                                             }

                                                                             @Override
                                                                             public void onSuccess (final Void modify)
                                                                             {
                                                                                 Info.display ("提示", "修改窗口成功");
                                                                                 List <PdsPrescDetailInfoModel> type=putDrugresult.isEmpty ()?unPutDrugresult:putDrugresult;
                                                                                 if ("0".equals (type.get (0)
                                                                                              .getPrescType ()))
                                                                                 {
                                                                                     printPrescInfo (
                                                                                                     "没有数据可供打印",
                                                                                                     "consumeRecpt2.xml",
                                                                                                     windowName);
                                                                                     
                                                                                 }
                                                                                 else
                                                                                 {
                                                                                     printPrescInfo (
                                                                                                     "没有数据可供打印",
                                                                                                     "consumeRecpt.xml",
                                                                                                     windowName);
                                                                                 }
                                                                                 
                                                                                 //打印摆药单
                                                                                 if(!putDrugresult.isEmpty ()){
                                                                                     printPutDrug ("putDrug.xml", windowName,putDrugresult);
                                                                                 }
                                                                                 if(!unPutDrugresult.isEmpty ()){
                                                                                     //打印未摆药单
                                                                                     printPutDrug ("unPutDrug.xml", windowName,unPutDrugresult);  
                                                                                 }
                                                                                 //清理缓存
                                                                                 prescresult.clear ();
                                                                                 unPutDrugresult.clear ();
                                                                                 putDrugresult.clear ();
                                                                                 // 清屏
                                                                                 final AppEvent event1 = new AppEvent (
                                                                                                                       RecipeFeeModuleEvents.RECIPEFEE_CLEAR);
                                                                                 Dispatcher.forwardEvent (event1);
                                                                             }
                                                                         });
    }

    // 凭证号打印
    private void printPrescInfo (final String msg,
                                 final String path, final String windowName)
    {
        final String patientId = m_recipeFeeMainPanel.getPatentId ();
        final String pName = m_recipeFeeMainPanel.getPname ();
        final String remainMoney = m_recipeFeeMainPanel.getRefundMoney ();
        if (putDrugresult.isEmpty () && unPutDrugresult.isEmpty ())
        {
            MessageBox.alert ("警告", msg, null);
            return;
        }
        List <PdsPrescDetailInfoModel>printData=putDrugresult.isEmpty ()?unPutDrugresult:putDrugresult;
        Double totalPrice = 0.0;
        for (final PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescresult)
        {
            totalPrice += pdsPrescDetailInfoModel.getCosts ();
        }
        final DynamicPrintModel dynamicPrintModel = new DynamicPrintModel ();
        // 表格动态数据
        final List <GridDataSetModel> gridDataList = new ArrayList <GridDataSetModel> ();
        final GridDataSetModel gridDataSetModel = new GridDataSetModel ("Grid");
        for (final PdsPrescDetailInfoModel pdsPackageInfoModel : prescresult)
        {
            final List <String> attributeList = new ArrayList <String> ();
            attributeList.add ("处方号");
            attributeList.add (ClientUtils.avoidNull(pdsPackageInfoModel.getPrescNo ()));
            attributeList.add ( ClientUtils.formatNumTwo (pdsPackageInfoModel.getTotalPrice ()));
            GridRowModel gridRowModel=new GridRowModel ();
            gridRowModel.setColumnValues (attributeList);
            gridDataSetModel.addAttributeValue (gridRowModel);
        }
        gridDataList.add (gridDataSetModel);
        // 静态数据
        final Map <String, String> keyValueMap = new HashMap <String, String> ();
        final String date = DateTimeFormat.getFormat ("yyyy-MM-dd HH:ss:mi").format (new Date ());
        keyValueMap.put ("consumeNo", ClientUtils.avoidNull (printData.get (0).getRcptNo ()));
        keyValueMap.put ("recptNo", recptNo);
        keyValueMap.put ("window", ClientUtils.avoidNull (windowName));
        keyValueMap.put ("patientId", ClientUtils.avoidNull(patientId));
        keyValueMap.put ("pName", ClientUtils.avoidNull(pName));
        keyValueMap.put ("remainMoney", ClientUtils.avoidNull(remainMoney));
        keyValueMap.put ("date", ClientUtils.avoidNull(date));
        keyValueMap.put ("performBy", ClientUtils.avoidNull(ClientUtils.getOrgModel().getOrgName()));
        keyValueMap.put ("totalPrice", ClientUtils.formatNumTwo (totalPrice) + "");
        keyValueMap.put ("Report--DataSets--DataSet_Grid::rowCount", printData.size ()+"");

        dynamicPrintModel.setPath (path);
        dynamicPrintModel.setKeyValueMap (keyValueMap);//静态数据
        dynamicPrintModel.setGridDataList (gridDataList);//动态数据
        //dynamicPrintModel.setPrinterName ("凭证打印机");
        PrintUtils.printDynamicReport (m_editorPanel, dynamicPrintModel, null);
    }
    // 摆药或者未摆药单打印
    private void printPutDrug (final String path, final String windowName,List <PdsPrescDetailInfoModel>prescList)
    {
        
        final String patientId = m_recipeFeeMainPanel.getPatentId ();
        final String pName = m_recipeFeeMainPanel.getPname ();
        final String remainMoney = m_recipeFeeMainPanel.getRefundMoney ();
        if (prescList.isEmpty ())
        {
            return;
        }
        Double totalPrice = 0.0;
        for (final PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescList)
        {
            totalPrice += pdsPrescDetailInfoModel.getCosts ();
        }
        final DynamicPrintModel dynamicPrintModel = new DynamicPrintModel ();
        // 表格动态数据
        final List <GridDataSetModel> gridDataList = new ArrayList <GridDataSetModel> ();
        final GridDataSetModel gridDataSetModel = new GridDataSetModel ("Grid");
        List <String>groupList=getPutDrugInfo (prescresult,prescList);
        for (String string : groupList)
        {
            final List <String> attributeList = new ArrayList <String> ();
            attributeList.add (string);
            GridRowModel gridRowModel=new GridRowModel ();
            gridRowModel.setColumnValues (attributeList);
            gridDataSetModel.addAttributeValue (gridRowModel);
        }
        gridDataList.add (gridDataSetModel);
        // 静态数据
        final Map <String, String> keyValueMap = new HashMap <String, String> ();
        final String date = DateTimeFormat.getFormat ("yyyy-MM-dd HH:ss:mi").format (new Date ());
        keyValueMap.put ("consumeNo", ClientUtils.avoidNull (prescList.get (0).getRcptNo ()));
        keyValueMap.put ("recptNo", recptNo);//ClientUtils.avoidNull (prescList.get (0).getRcptNo ()
        keyValueMap.put ("window", ClientUtils.avoidNull (windowName));
        keyValueMap.put ("patientId", ClientUtils.avoidNull (patientId));
        keyValueMap.put ("pName", ClientUtils.avoidNull (pName));
        //keyValueMap.put ("age", ClientUtils.avoidNull (m_recipeFeeMainPanel.getAge ()));
        keyValueMap.put ("remainMoney",ClientUtils.avoidNull(remainMoney));
        keyValueMap.put ("date", ClientUtils.avoidNull(date));
        keyValueMap.put ("performBy", ClientUtils.avoidNull (dispensaryName));
        keyValueMap.put ("totalPrice", ClientUtils.formatNumTwo (totalPrice));
        keyValueMap.put ("Report--DataSets--DataSet_Grid::rowCount", prescList.size ()+"");
        dynamicPrintModel.setPath (path);
        dynamicPrintModel.setKeyValueMap (keyValueMap);
        dynamicPrintModel.setGridDataList (gridDataList);
        //dynamicPrintModel.setPrinterName ("摆药单");
       PrintUtils.printDynamicReport (m_editorPanel, dynamicPrintModel, null);
    }

    @SuppressWarnings ("unchecked")
    private void startPrint (Map<String,Object>map)
    {
        prescresult=(List <PdsPrescDetailInfoModel>)map.get ("prescDetails");
        for (final PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescresult)
        {
            if (!dispensaryCode.equals (pdsPrescDetailInfoModel.getPerformedBy ()))
            {//未出库明细
                unPutDrugresult.add (pdsPrescDetailInfoModel);   
            }else{
                putDrugresult.add (pdsPrescDetailInfoModel);
            }
        }
        final Dialog dialog =new Dialog();
        dialog.setHeading ("窗口分配到");
        dialog.setButtons (Dialog.OK);
        dialog.setHeight (53);
        dialog.setWidth (150);
        Button btn=dialog.getButtonById (Dialog.OK);
        dialog.setHideOnButtonClick(true);  
        final OutputWindowCombox combox=new OutputWindowCombox(dispensaryCode);
        PhamWindowConfigModel model=new PhamWindowConfigModel();
        if(!putDrugresult.isEmpty ()){
            model.setWindowName ((String)map.get ("windowName"));
            model.setPhamWindowConfigId ((Long)map.get ("windowId"));
        }
        combox.setValue (model);
        combox.setHeight (53);
        dialog.add (combox);
        dialog.show ();
        btn.addSelectionListener (new SelectionListener <ButtonEvent>()
        {
            
            @Override
            public void componentSelected (ButtonEvent ce)
            {
                final Long window =combox.getValue ().getPhamWindowConfigId ();
                final String windowName =combox.getValue ().getWindowName ();
                // 修改供药过程
                modifyWindow (window,windowName);
                return;
            }
        });
    }
    //得到摆药要打的数据或者未摆药要打的数据
    private List <String> getPutDrugInfo (final List <PdsPrescDetailInfoModel> prescresult,
                                   final List <PdsPrescDetailInfoModel> drugResult)
      {
          List <String>list=new ArrayList <String> ();
          
          for (PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescresult)
          {
              StringBuffer sb=new StringBuffer ("");
              //按处方号进行分组
              List <PdsPrescDetailInfoModel>prescLists=new ArrayList <PdsPrescDetailInfoModel> ();
              prescLists.add (pdsPrescDetailInfoModel);
              List <PdsPrescDetailInfoModel>putDrugList=ClientUtils.getPrescDetailSelected (prescLists, drugResult);
              sb.append ("处方号: "+pdsPrescDetailInfoModel.getPrescNo ()+"\n");
              for (int i = 0; i < putDrugList.size (); i++)
              {   
                  PdsPrescDetailInfoModel model=putDrugList.get (i);
                  sb.append ((i+1)+"  "+model.getPhamName ()+"\n"
                          +model.getPhamSpec ()+"\n"
                          +model.getQtySum ()+model.getQtyUnitName ()+"   "+model.getUnitQty ()+model.getPackageUnitsName ()+"   "+ClientUtils.avoidNull (model.getAllocation ())
                          +"\n"+"用法"+"   "+"每日"+model.getFreqTimeQty ()+"次     "+ClientUtils.avoidNull (model.getAdministrationName())+"   "+"每次"+model.getEachNumber ()+model.getDosageUnitsName ()
                          +"\n"+"备注"+ClientUtils.avoidNull (model.getMemo ())+"\n");
              }
              list.add(sb.toString ());
          }
          return list;
      }
}
